package com.dagene.weixin.service;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.dagene.weixin.bean.TextMessage;
import com.dagene.weixin.entity.ChatMsg;
import com.dagene.weixin.repository.NewtableDao;
import com.dagene.weixin.util.Constants;
import com.dagene.weixin.util.DateUtil;
import com.dagene.weixin.util.MessageUtil;

/**
 * 核心服务类
 * 
 * @author liufeng
 * @date 2013-05-20
 */
@Component
@Transactional
public class CoreService {

	private static Logger logger = LoggerFactory.getLogger(CoreService.class);

	@Autowired
	ChatUtilService chatUtilService;
	@Autowired
	UserService userService;
	@Autowired
	NewtableDao articleDao;

	/**
	 * 处理微信发来的请求
	 * 
	 * @param request
	 * @return
	 */
	public String processRequest(HttpServletRequest request) {
		String respMessage = null;
		// WeixinReg currentUser = null;
		TextMessage textMessage = new TextMessage();
		try {
			// 默认返回的文本消息内容
			String respContent = "请求处理异常，请稍候尝试！";

			// xml请求解析
			Map<String, String> requestMap = MessageUtil.parseXml(request);

			// 发送方帐号（open_id）
			String fromUserName = requestMap.get("FromUserName");

			// 公众帐号
			String toUserName = requestMap.get("ToUserName");
			// 消息类型
			String msgType = requestMap.get("MsgType");

			// 消息创建时间
			String createTimeStr = requestMap.get("CreateTime");

			String reqContent = requestMap.get("Content");

			reqContent = reqContent == null ? "" : reqContent.trim();

			ChatMsg chatmsg = new ChatMsg();
			// 用户
			chatmsg.setOpenid(fromUserName);
			// 消息类型
			chatmsg.setMsgtype(msgType);
			// 时间
			chatmsg.setTime(DateUtil.UnixTimeToDate(createTimeStr));

			// 回复文本消息
			textMessage.setToUserName(fromUserName);
			textMessage.setFromUserName(toUserName);
			textMessage.setCreateTime(new Date().getTime());
			textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
			textMessage.setFuncFlag(0);

			// 文本消息
			if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
				respMessage = processTextRequest(request, chatmsg, textMessage,
						reqContent);
			}
			// 图片消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
				respMessage = processImageRequest(requestMap, chatmsg,
						textMessage);
			}
			// 地理位置消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {
				respMessage = "您发送的是地理位置消息！";
			}
			// 链接消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {
				respMessage = "您发送的是链接消息！";
			}
			// 音频消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {
				respMessage = processVoiceRequest(requestMap, chatmsg,
						textMessage);
			}
			// 事件推送
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
				// 事件类型
				String eventType = requestMap.get("Event");

				if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
					// 订阅
					respContent = "您好，欢迎关注迪安诊断技术服务";
				} else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
					// 取消订阅
				}
				// 自定义菜单点击事件
				else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {

					String eventKey = requestMap.get("EventKey");
					System.out.println(eventKey);
					if (eventKey.equals("400")) {
						ChatMsg chatmsg1 = new ChatMsg();
						synchronized (chatmsg1) {
							chatmsg1.setOpenid(chatmsg.getOpenid());
							chatmsg1.setMsgtype(chatmsg.getMsgtype());
							chatmsg1.setTime(chatmsg.getTime());
							respContent = chatUtilService
									.requestCustomerService(request, chatmsg1);
						}
					}
				} else if (eventType.equals("SCAN")) {

				}
				textMessage.setContent(respContent);
				respMessage = MessageUtil.textMessageToXml(textMessage);
			}
		} catch (NoRegException e) {
			// 回复文本消息
			/*
			 * textMessage
			 * .setContent("<a href=\"http://weixindianren.dazd.cn/reg/init?weixin="
			 * + textMessage.getToUserName() + "\">您还未登录，请点击登录用户</a> ");
			 * respMessage = MessageUtil.textMessageToXml(textMessage);
			 */
		} catch (Exception e) {
			e.printStackTrace();
		}
		return respMessage;
	}

	private String processImageRequest(Map<String, String> requestMap,
			ChatMsg chatmsg, TextMessage textMessage) throws Exception {

		chatUtilService.processMedia(requestMap, chatmsg);

		return "success";
	}

	private String processVoiceRequest(Map<String, String> requestMap,
			ChatMsg chatmsg, TextMessage textMessage) throws Exception {

		chatUtilService.processMedia(requestMap, chatmsg);

		return "success";

	}

	private String processTextRequest(HttpServletRequest request,
			ChatMsg chatmsg, TextMessage textMessage, String reqContent)
			throws NoRegException {
		String respMessage = "";
		String respContent = "";
		try {
			ChatMsg chatmsg1 = new ChatMsg();
			chatmsg1.setOpenid(chatmsg.getOpenid());
			chatmsg1.setMsgtype(chatmsg.getMsgtype());
			chatmsg1.setTime(chatmsg.getTime());

			if (reqContent.indexOf("注册") >= 0) {
				respContent = "<a href=\""
						+ getAuthURl(Constants.weixinurl
								+ "/weixiu/register.html") + "\">点击注册账号</a> ";
			} else if (reqContent.equals("400")) {
				respContent = chatUtilService.requestCustomerService(request,
						chatmsg1);
			}
			// 正在聊天中或者客服回复编号进行聊天
			else if (chatUtilService.isInChat(chatmsg.getOpenid())
					|| chatUtilService.isMallCustomerService(
							chatmsg.getOpenid(), reqContent)) {
				// 处理聊天
				respContent = chatUtilService.processChat(reqContent, chatmsg1);
				if (respContent.equals("success")) {
					return respContent;
				}
			} else {
				respContent = "感谢您的留言！";
			}
			textMessage.setContent(respContent);
			respMessage = MessageUtil.textMessageToXml(textMessage);

		} catch (Exception e) {

			e.printStackTrace();
		}
		return respMessage;

	}

	public static String getAuthURl(String in) {
		try {
			return "https://open.weixin.qq.com/connect/oauth2/authorize?appid="
					+ Constants.APPID
					+ "&redirect_uri="
					+ java.net.URLEncoder.encode(in, "utf-8")
					+ "&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return in;
	}
}
